package com.mao.demo4;


import com.mao.demo4.Rent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //代理接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    //根据实现类接口生成相应的代理
    public Object getProxy(){

        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);

    }


    //处理代理实例，并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("代理开始");
        //动态代理的本质，通过反射机制实现
        log(method.getName());
        Object result = method.invoke(target,args);
        System.out.println("代理结束");

        return result;
    }

    public void log(String msg){

        System.out.println("执行了" + msg + "方法");

    }


}
